package com.brrbaii.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.brrbaii.Exception.BusinessException;
import com.brrbaii.common.ErrorCode;
import com.brrbaii.mapper.UserMapper;
import com.brrbaii.model.dto.UserQueryDTO;
import com.brrbaii.model.entity.User;
import com.brrbaii.service.UserService;
import com.brrbaii.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static com.brrbaii.common.StrConstants.*;


/**
* @author 白日日白
* @description 针对表【tb_user(用户表)】的数据库操作Service实现
* @createDate 2023-12-22 22:45:20
*/
@Service
@Slf4j

public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public long userRegister(String username, String userPassword, String checkPassword) {
        // 1、检验
        if (StringUtils.isAnyBlank(username, userPassword, checkPassword)){
            throw new BusinessException(ErrorCode.NULL_ERROR,PARAMS_IS_NULL);
        }
        if (username.length() < MIN_USER_NAME){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,USERNAME_TOO_SHORT);
        }
        if (userPassword.length() < MIN_USER_PASSWORD || checkPassword.length() < MIN_USER_PASSWORD) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,PASSWORD_TOO_SHORT);
        }
        // 账户不包含特殊字符
        if(!ReUtil.contains(USERNAME_VERIFICATION_PATTERN,username)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,INVALID_NAME);
        }
        //账户不重复
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(User::getUsername,username);
        long count = count(lambdaQueryWrapper);
        if( count > 0 ){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,USER_ALREADY_EXIST);
        }
        //两次密码一致
        if(!userPassword.equals(checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,CHECK_PASSWORD_NOT_SAME);
        }
        //hutool加密
        String md5UserPassword = SecureUtil.md5(userPassword);
        User user = new User();
        user.setUsername(username);
        user.setPassword(md5UserPassword);
        //防止long和Long拆箱错误
        boolean save = this.save(user);
        if(!save){
            return -1;
        }
        return user.getId();
    }



    @Override
    public User userLogin(String username, String userPassword, HttpServletRequest request) {
        // 1、检验
        if (StringUtils.isAnyBlank(username, userPassword)){
            throw new BusinessException(ErrorCode.NULL_ERROR,PARAMS_IS_NULL);
        }
        if (username.length() < MIN_USER_NAME){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,USERNAME_TOO_SHORT);
        }
        if (userPassword.length() < MIN_USER_PASSWORD) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,PASSWORD_TOO_SHORT);
        }
        // 账户不包含特殊字符
        if(!ReUtil.contains(USERNAME_VERIFICATION_PATTERN,username)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,INVALID_NAME);
        }
        //hutool加密
        String md5UserPassword = SecureUtil.md5(userPassword);
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUsername,username);
        userLambdaQueryWrapper.eq(User::getPassword,md5UserPassword);
        User user = userMapper.selectOne(userLambdaQueryWrapper);
        if(user == null){
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR,CHECK_USER_EXIST);
        }
        //2、记录用户登录态
        request.getSession().setAttribute(USER_LOGIN_STATE,user);
        //3、用户脱敏
        return user;

    }

    @Override
    public List<User> queryUserByName(UserQueryDTO userQueryDTO) {
        if(!isAdmin()){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        // 传参了，按参数查，没传则查全部
        User user = new User();
        if(userQueryDTO != null){
            BeanUtil.copyProperties(userQueryDTO,user);
        }
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>(user);
        List<User> userList = this.list(userLambdaQueryWrapper);
        return userList;
    }

    @Override
    public boolean deleteUserById(long id) {
        if(!isAdmin()){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        if ( id <= USER_NOT_EXIST_CODE ){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,USER_NOT_EXIST);
        }
        return this.removeById(id);
    }

    /**
     * 是否为管理员
     * @param
     * @return
     */
    public boolean isAdmin(){
        //鉴权
        User user = UserHolder.getUser();
        if(user == null || user.getRole() != ADMIN_ROLE ){
            log.info("The current user has insufficient permissions. Please contact the administrator");
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        return true;
    }

}




